package com.jackchong.widget

import android.annotation.SuppressLint
import android.content.Context
import android.content.res.Resources
import android.content.res.TypedArray
import android.graphics.Paint
import android.graphics.Typeface
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextUtils
import android.text.style.AbsoluteSizeSpan
import android.text.style.ForegroundColorSpan
import android.util.AttributeSet
import android.view.View
import android.widget.TextView
import androidx.annotation.StringRes
import com.jackchong.base.BaseApplication
import com.jackchong.utils.JAuto
import com.utils.R

/**
 * 作者: jack(黄冲)
 * 邮箱: 907755845@qq.com
 * create on 2018/11/20 13:58
 */
@SuppressLint("AppCompatCustomView")
class JTextView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0,
    defStyleRes: Int = 0
) : TextView(context, attrs, defStyleAttr, defStyleRes) {

    var onSelectedChangeListener: ((v: View, selected: Boolean) -> Unit)? = null
    private var mHintSize = 0f
    private var mTypeface: Typeface? = null
    private var mHintTypeface: Typeface? = null
    private var firstText: String? = null
    private var firstTextSize = 0f
    private var firstTextColor = 0
    private var lastText: String? = null
    private var lastTextSize = 0f
    private var lastTextColor = 0

    private object TextStyle {
        /* 粗体 */
        const val BOLD = 1

        /* 斜体 */
        const val ITALIC = 2

        /* 常规 */
        const val NORMAL = 3
    }

    init {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.JTextView)
        parseAttr(typedArray)
        typedArray.recycle()
    }


    private fun parseAttr(typedArray: TypedArray) {
        val pLine = typedArray.getBoolean(R.styleable.JTextView_JText_P, false)
        val text = typedArray.getString(R.styleable.JTextView_JText)
        firstText = typedArray.getString(R.styleable.JTextView_JFirstText)
        firstTextSize =
            JAuto.auto(typedArray.getDimension(R.styleable.JTextView_JFirstTextSize, 0f))
        firstTextColor = typedArray.getColor(R.styleable.JTextView_JFirstTextColor, 0)
        lastText = typedArray.getString(R.styleable.JTextView_JLastText)
        lastTextSize = JAuto.auto(typedArray.getDimension(R.styleable.JTextView_JLastTextSize, 0f))
        lastTextColor = typedArray.getColor(R.styleable.JTextView_JLastTextColor, 0)
        if (firstText != null || lastText != null) {
            post { setText(getText()) }
        }
        val select = typedArray.getBoolean(R.styleable.JTextView_JSelect, false)
        if (select) {
            isSelected = select
        }
        if (!TextUtils.isEmpty(text) && !BaseApplication.RELEASE_MODE) {
            setText(text)
        }
        if (pLine) {
            paint.flags = Paint.UNDERLINE_TEXT_FLAG
        }
        mHintSize = JAuto.auto(typedArray.getDimension(R.styleable.JTextView_JHintSize, 0f))
        val hintTextStyle = typedArray.getInt(R.styleable.JTextView_JHintTextStyle, 0)
        val textStyle = typedArray.getInt(R.styleable.JTextView_JTextStyle, 0)
        if (hintTextStyle == TextStyle.BOLD) {
            mHintTypeface = Typeface.defaultFromStyle(Typeface.BOLD)
        } else if (hintTextStyle == TextStyle.ITALIC) {
            mHintTypeface = Typeface.defaultFromStyle(Typeface.ITALIC)
        } else if (hintTextStyle == TextStyle.NORMAL) {
            mHintTypeface = Typeface.defaultFromStyle(Typeface.NORMAL)
        }
        if (textStyle == TextStyle.BOLD) {
            mTypeface = Typeface.defaultFromStyle(Typeface.BOLD)
        } else if (textStyle == TextStyle.ITALIC) {
            mTypeface = Typeface.defaultFromStyle(Typeface.ITALIC)
        } else if (textStyle == TextStyle.NORMAL) {
            mTypeface = Typeface.defaultFromStyle(Typeface.NORMAL)
        }
    }

    override fun setPressed(pressed: Boolean) {
        super.setPressed(pressed)
        val alpha = if (pressed && isClickable) 0.8f else 1f
        if (alpha != getAlpha()) {
            setAlpha(alpha)
        }
    }

    fun text(): String {
        return text.toString()
    }

    fun text(text: CharSequence?) {
        super.setText(text)
    }

    fun firstText(text: CharSequence?) {
        val content = getText()
        firstText = text?.toString() ?: ""
        setText(content)
    }

    fun firstText(stringRes: Int) {
        val content = context.getString(stringRes)
        firstText = context.getString(stringRes)
        text = content
    }

    fun lastText(text: CharSequence?) {
        val content = getText()
        lastText = text?.toString() ?: ""
        setText(content)
    }

    fun lastText(stringRes: Int) {
        val content = context.getString(stringRes)
        lastText = context.getString(stringRes)
        text = content
    }

    override fun getText(): CharSequence {
        val text = super.getText()
        var s = text.toString()
        if (firstText != null) {
            s = s.replace(firstText!!, "")
        }
        if (lastText != null) {
            s = s.replace(lastText!!, "")
        }
        return s
    }

    override fun setText(text: CharSequence, type: BufferType) {
        if (TextUtils.isEmpty(text) && mHintTypeface != null) {
            paint.typeface = mHintTypeface
        } else if (mTypeface != null) {
            paint.typeface = mTypeface
        }
        if (text is String) {
            val firstText = firstText?: ""
            val lastText = lastText?: ""
            val builder = SpannableStringBuilder(firstText + text.toString() + lastText)
            if (firstText.isNotEmpty()) {
                val firstTextColor = if (firstTextColor == 0) currentTextColor else firstTextColor
                val firstTextSize = if (firstTextSize == 0f) textSize else firstTextSize
                builder.setSpan(
                    ForegroundColorSpan(firstTextColor),
                    0,
                    firstText.length,
                    Spanned.SPAN_INCLUSIVE_INCLUSIVE
                )
                builder.setSpan(
                    AbsoluteSizeSpan(firstTextSize.toInt(), false),
                    0,
                    firstText.length,
                    Spanned.SPAN_INCLUSIVE_INCLUSIVE
                )
            }
            if (lastText.isNotEmpty()) {
                val lastTextColor = if (lastTextColor == 0) currentTextColor else lastTextColor
                val lastTextSize = if (lastTextSize == 0f) textSize else lastTextSize
                builder.setSpan(
                    ForegroundColorSpan(lastTextColor),
                    builder.length - lastText.length,
                    builder.length,
                    Spanned.SPAN_INCLUSIVE_INCLUSIVE
                )
                builder.setSpan(
                    AbsoluteSizeSpan(lastTextSize.toInt(), false),
                    builder.length - lastText.length,
                    builder.length,
                    Spanned.SPAN_INCLUSIVE_INCLUSIVE
                )
            }
            super.setText(builder, type)
            return
        }
        super.setText(text, type)
    }

    fun text(@StringRes resid: Int) {
        try {
            super.setText(resid)
        } catch (e: Resources.NotFoundException) {
            super.setText(resid.toString())
        }
    }

    override fun setSelected(selected: Boolean) {
        super.setSelected(selected)
        onSelectedChangeListener?.invoke(this, selected)
    }
}